import { defineStore } from 'pinia'
import { ElNotification } from 'element-plus'
import router from '/@/router'

export const useNewsStore = defineStore('news', {
    state: () => {
        return {
            hasNewOrder: false,
            volume: 70,
            notifyList: []
        }
    },
    actions: {
        getOrderNotify() {
          let _this = this
          sa.ajax('/api/webOnlineInquiry/getLatestOnlineInquiry', {}, function (res) {
            console.log('getNewsList',res)
            let data = res.data
            if (!data) return
            // 判断该订单消息是否已经存在
            if (_this.notifyList.find(item => item.OnlineInquiryId == data.OnlineInquiryId)) {
              return
            }
            _this.notifyList.push(data) 
            if (data.OnlineInquiryId) {
              _this.setHasNewOrder(true)
            }
             // 使用Web Speech API进行语音播报
            if ('speechSynthesis' in window) {
                console.log('支持Web Speech API')
                let speech = new SpeechSynthesisUtterance();
                speech.text = "您有新的问诊订单，请及时处理";
                speech.lang = 'zh-CN';
                window.speechSynthesis.speak(speech);
            }

            var notifyModal =  ElNotification({
              title: '新订单通知',
              message: `您有新的问诊订单，请及时处理(${data.OnlineInquiryNo})`,
              position: 'bottom-right',
              duration: 0,
              onClick: () => {
                notifyModal.close()
                router.push({
                  path: '/store-wait-consultation',
                  query: {
                    OnlineInquiryId: data.OnlineInquiryId,
                    OnlineInquiryNo: data.OnlineInquiryNo,
                    v: Date.now()
                  }
                })
              }
            })
          },{
            msg: false
          })
        },
        setHasNewOrder(val) {
            this.hasNewOrder = val
        },
    }
})